package com.avic.controller;

import com.avic.common.constant.SystemLogConstant;
import com.avic.common.enums.MapVideoStateEnums;
import com.avic.common.util.PlUploadUtils;
import com.avic.common.util.lang.BaseResponse;
import com.avic.common.util.lang.ServiceCallBack;
import com.avic.controller.info.PlUpload;
import com.avic.dal.model.MapVideo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @Author huangsheng on 2019/2/27
 */
@Slf4j
@RestController
@RequestMapping("video")
@Api(tags = "视频录制记录管理", description = "视频录制记录管理")
public class MapVideoController extends AbstractFacadeImpl {

    /**
     * Plupload文件上传处理方法
     */
    @PostMapping(value = "/upload/{videoId}")
    public BaseResponse upload(PlUpload plUpload, @PathVariable("videoId") int videoId, HttpServletRequest request) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {

            @Override
            public void check() throws Exception {
            }

            @Override
            public void doService() throws Exception {
                // 手动传入Plupload对象HttpServletRequest属性
                plUpload.setRequest(request);

                // 文件存储绝对路径
                File fileDir = new File(commonProperties.getUploadLocation() + commonProperties.getPluploadVideoPrefix());
                if (!fileDir.exists()) {
                    fileDir.mkdirs();// 可创建多级目录，而mkdir()只能创建一级目录
                }
                // 在服务器内生成唯一文件名
                String fileName = Integer.toHexString((int) System.currentTimeMillis()) + "-" + plUpload.getName();
                // 开始上传文件
                PlUploadUtils.upload(plUpload, fileDir, fileName);
                if (plUpload.getChunks() - plUpload.getChunk() == 1) {
                    MapVideo mapVideoDB = mapVideoService.queryMapVideoRecord(videoId);
                    if (null != mapVideoDB) {
                        // 文件上传结束了，判断文件是是否存在，存在则，更新数据库数据;修改文件名称
                        File uploadFileDir = new File(commonProperties.getUploadLocation() + commonProperties.getPluploadVideoPrefix() + fileName);
                        if (fileDir.exists()) {
                            log.info("文件上传成功,更新数据库数据");
                            MapVideo mapVideo = new MapVideo();
                            try {
                                mapVideo.setId(videoId);
                                mapVideo.setVideoName(fileName);
                                mapVideo.setVideoPath(commonProperties.getPluploadVideoPrefix() + fileName);
                                mapVideo.setVideoState(MapVideoStateEnums.UPLOADED.getState());
                                mapVideoService.uploadUpdateVideo(mapVideo);
                            } catch (Exception e) {
                                log.warn("更改数据库发生错误，删除上传的文件");
                                uploadFileDir.delete();
                            }
                            // 新建系统日志
                            systemServiceFeignService.createSystemLog(
                                    String.format(SystemLogConstant.UPDATE_VIDEO,
                                            mapVideo.getVideoName(), commonProperties.getViewFilePrefix() + mapVideo.getVideoPath()), mapVideoDB.getCreateUserId());
                        } else {
                            log.info("文件上传失败,需要重新上传");
                            MapVideo mapVideo = new MapVideo();
                            mapVideo.setId(videoId);
                            mapVideo.setVideoState(MapVideoStateEnums.UPLOAD_FAILED.getState());
                            mapVideoService.uploadFailedUpdateVideo(mapVideo);

                            // 新建系统日志
                            systemServiceFeignService.createSystemLog(
                                    String.format(SystemLogConstant.UPDATE_VIDEO_FAILD, plUpload.getName()), mapVideoDB.getCreateUserId());
                        }
                    }
                }
                result.setSuccess(true);
            }
        });
    }
}
